<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <input id="ajaxBtn" type="button" value="ajax">
    <input type="text" id="username" >
    <script>
        document.getElementById("ajaxBtn").onclick = function(){

            // 1. 创建XHR对象
            let xhr = new XMLHttpRequest();
            // 2. 打开连接
            xhr.open('get','/students/findById?id=630c24411849ac7430bf1229');
            // 3. 发送请求
            xhr.send();
            // 4. 接收服务器的响应并处理
            xhr.onreadystatechange = function(){
                if(xhr.readyState == 4 && xhr.status == 200){
                    let students = JSON.parse(xhr.responseText);
                    console.log(students);
                   
                }
            }
        };
        document.getElementById("username").onblur = function(){
            // 1. 创建XHR对象
            let xhr = new XMLHttpRequest();
            // 2. 打开连接
            xhr.open('post','/users/usernameExist');
            // 如果是post提交并带有参数，那么必须设置Content-type请求头
            xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
            // 3. 发送请求
            xhr.send("username="+this.value);
            // 4. 接收服务器的响应并处理
            xhr.onreadystatechange = function(){
                if(xhr.readyState == 4 && xhr.status == 200){
                    let data = JSON.parse(xhr.responseText);
                    console.log(data);
                   
                }
            }
        }
    </script>
</body>
</html>